<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple
          collapse-tags clearable filterable />
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <el-input v-model="form.skuInfo.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <VBatchInput v-model="form.deliver_no" placeholder="发货单号" @search="query" class="w-44" />
        <VBatchInput v-model="form.supplier_code" placeholder="供应商id" @search="query" class="w-44" />
        <VBatchInput v-model="form.supplier_coding" placeholder="供应商简码" @search="query" class="w-44" />
        <VBatchInput v-model="form.inspection_no" placeholder="外验编号" @search="query" class="w-44" />
        <VSelect v-model="form.inspection_type" placeholder="类型" :options="options.inspection_type" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.inspection_result" placeholder="验货结果" :options="options.inspection_result" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VCascader v-model="form.inspection_user_id" placeholder="验货人" multiple collapse-tags filterable clearable
          style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">实际验货时间</div>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/manage/sale/report" type="primary" @click="handleBatch('report')">生成验货报告</VButton>
        <VButton auth="/purchase/manage/sale/cancel" @click="handleBatch('cancel')">批量作废</VButton>
        <VImport auth="/purchase/manage/sale/import" :tableRef="tableRef"
          importUrl="/v1/external-inspection/inspection-report/import"
          downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/inspection_report_template.xlsx"
          class="ml-auto" @success="query" />
        <VExport auth="/purchase/manage/sale/export" mainKey="ir_id" :name="baseName" :tableRef="tableRef" task />
      </template>
    </VTable>
    <Upload ref="uploadRef" :options="options" @success="query" />
    <Enter ref="enterRef" :options="options" @success="query" />
    <Contract ref="contractRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import api from './api'

import VImport from '@/components/VImport'

import Upload from './components/Upload'
import Enter from './components/Enter'
import Contract from './components/Contract'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { download } from '@/utils'

const baseName = 'inspection_report'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'purchase' }).then(res => res.data),
  getOption({ type: 'external_inspection' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const contractRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (name !== 'report' && !selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const ir_ids = selection.map(d => d.ir_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    cancel: () => {
      showLoading()
      api.batchCancel({ ir_ids }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    report: () => {
      showLoading()
      api.processReport({ ir_ids, ...tableRef.value.getQueryForm() }).then(res => {
        ElMessage.success('操作成功')
        download(res.data.url)
      }).finally(closeLoading)
    },
  }
  handle[name]()
}

// 单行操作
const uploadRef = ref()
const enterRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { ir_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    download: () => {
      api.download({ ir_id }).then(res => {
        download(res.data.url)
      })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 92 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      skuInfo: { type: 'sku', value: '' },
      dateRange: { type: 'inspection_date', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      width: 150, slots: {
        header: () => <div>外验编号<br />实际验货日期<br/>验货人</div>,
        default: ({ row }) => <div>
          <VText value={row.inspection_no} />
          <VText value={row.inspection_date} />
          <VText value={row.inspection_user} />
        </div>
      }
    },
    {
      width: 80, slots: {
        header: () => <div>类型</div>,
        default: ({ row }) => <VText>{row.report_type_name}</VText>
      }
    },
    {
      width: 240, slots: {
        header: () => <div>供应商信息</div>,
        default: ({ row }) => <div>
          <VText title='供应商' value={row.supplier_name}></VText>
          <VText title='供应商id' value={row.supplier_code} />
        </div>
      }
    },
    {
      width: 160, slots: {
        header: () => <div>采购单<br />采购人员</div>,
        default: ({ row }) => <div>
          <VText>{row.purchase_no}</VText>
          <VText>{row.purchase_user}</VText>
        </div>
      }
    },
    {
      width: 120, slots: {
        header: () => <div>sku<br />透明计划</div>,
        default: ({ row }) => <div>
          <VText>{row.sku}</VText>
          <VText>{row.is_transparent_name}</VText>
        </div>
      }
    },
    {
      title: '图片', width: 100, slots: {
        default: ({ row }) => <VImage src={row.main_img} size="80px"></VImage>
      }
    },
    {
      width: 140, slots: {
        header: () => <div>产品名称</div>,
        default: ({ row }) => <VText value={row.sku_name} line={3} />
      }
    },
    {
      width: 240, slots: {
        header: () => <div>备库发货信息</div>,
        default: ({ row }) => <div>
          <VText title='发货单号'>{row.deliver_no[0]?.deliver_no}</VText>
          <VText title='发货数量'>{row.deliver_no[0]?.deliver_num}</VText>
          <VText title='预计发货时间'>{row.deliver_no[0]?.except_deliver_time}</VText>
          <VText title='交货方式'>{row.deliver_no[0]?.deliver_method_name}</VText>
        </div>
      }
    },
    {
      width: 160, slots: {
        header: () => <div>系统产品尺寸</div>,
        default: ({ row }) => <div>
          <VText title='长cm'>{row.system_length}</VText>
          <VText title='宽cm'>{row.system_width}</VText>
          <VText title='高cm'>{row.system_high}</VText>
          <VText title='单箱重量'>{row.system_unit_weight}</VText>
        </div>
      }
    },
    {
      width: 160, slots: {
        header: () => <div>QA实测数据</div>,
        default: ({ row }) => <div>
          <VText title='长cm'>{row.actually_length}</VText>
          <VText title='宽cm'>{row.actually_width}</VText>
          <VText title='高cm'>{row.actually_high}</VText>
          <VText title='单箱重量'>{row.actually_weight}</VText>
        </div>
      }
    },
    {
      width: 100, title: '总箱数（箱）', field: 'total_box'
    },
    {
      width: 120, title: '事业部', field: 'department'
    },
    {
      width: 120, slots: {
        header: () => <div>数量信息</div>,
        default: ({ row }) => <div>
          <VText title='交货数'>{row.provide_num}</VText>
          <VText title='抽检数量'>{row.check_num}</VText>
          <VText title='不良数'>{row.reject_num}</VText>
          <VText title='不良率'>{row.reject_percent}</VText>
        </div>
      }
    },
    {
      width: 100, slots: {
        header: () => <div>不良描述</div>,
        default: ({ row }) => <VText value={row.reject_content} line={3} />
      }
    },
    { title: '验货结果', field: 'inspection_result_name', width: 106, slots: {
      header: () => <div>验货结果<br/>是否二次验货</div>,
      default: ({ row }) => <div>
        <VText value={row.inspection_result_name} />
        <VText value={row.is_second_inspection_name} />
      </div>
    } },
    {
      width: 100, slots: {
        header: () => <div>解决方案</div>,
        default: ({ row }) => <VText value={row.solution} line={3} />
      }
    },
    {
      width: 120, slots: {
        header: () => <div>备注说明</div>,
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { billing_status } = row
          return <div class='nm flex flex-col gap-1'>
            <VButton auth="/purchase/manage/sale/download" link type="primary" onClick={() => handleRow('download', row)}>下载验货报告</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>